// pages/index/index.js
var app = getApp();
import { index,newsapi } from '../../config/https';
import Notify from '../../vant/notify/notify';
import Dialog from '../../vant/dialog/dialog';
import Toast from '../../vant/toast/toast';
import { getLocation } from "../../config/authorization";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDistrict: false, //地址弹窗
    isNotice: false, //消息弹窗
    latitude: null, //纬度
    longitude: null, //经度
    city: null,//城市名称
    is_open: 0, //是否开通服务0=>未开通，1=>已开通
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.session(() => {
      const is_open = app.globalData.is_open
      if (is_open == 1) {
        const location = app.globalData.location
        this.setData(location)
        this.init()
      } else {
        Notify({
          text: '位置获取中请稍后...',
          duration: 0,
          backgroundColor: '#1989fa'
        });
        getLocation().then(res => {
          this.succNot('位置获取成功')
          this.setData(res)
          this.init()
        }).catch(err => {
          if (err.status == 1) {
            Dialog.confirm({
              confirmButtonOpenType: 'openSetting',
              message: '获取微信定位失败，请授权小程序获取位置信息'
            }).catch(res => {
              this.failNot(err.msg || '获取微信定位失败,请稍后再试！')
              this.init()
            });
          } else if (err.status == 2){
            this.failNot(err.msg || '获取微信定位超时,请稍后再试！')
            this.init()
          } else {
            this.failNot(err.msg || '获取微信定位失败,请稍后再试！')
            this.init()
          }
        })
      }
    })
  },
  
  // 在打开授权设置页后回调
  bindopensetTap(e){
    e.detail.authSetting['scope.userLocation'] && this.onLoad()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  init(){
    Toast.loading({
      mask: true,
      message: '请稍后...'
    });
    index({
      user_id: app.globalData.user_id,
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      coordinates_city: this.data.city
    }).then(res => {
      res.isNotice = res.article_window && true
      res.member = res.member.splice(0,8);
      this.setData(res);
      let cateArr = [];
      res.nav.forEach(item => {
        cateArr.push({
          one_cate: item.id,
          two_cate: null,
        })
      });
      app.globalData.vanTab.cate = cateArr;
      const is_open = Number(res.is_open) || 0
      app.globalData.customer = res.customer
      app.globalData.is_open = is_open
      if (is_open == 0){
        Dialog.confirm({
          message: '当前城市未开通服务，是否切换城市为南昌？'
        }).then(res => {
          this.setData(app.globalData.location)
          this.init()
          app.globalData.is_open = 1
        }).catch(err => {

        });
      }else{
        app.globalData.location = {
          latitude: this.data.latitude,
          longitude: this.data.longitude,
          city: this.data.city
        }
      }
      // 停止下拉刷新
      wx.stopPullDownRefresh();
      Toast.clear()
    }).catch( err => {
      Toast.clear()
    })
  },

  succNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#1989fa'
    });
  },

  failNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#f44'
    });
  },

  // 地址弹窗
  onDistrict(){
    this.setData({
      isDistrict: !this.data.isDistrict
    })
  },
  districtTap(){
    Toast.loading({
      mask: true,
      message: '请稍后...'
    });
    this.setData(Object.assign(app.globalData.location,{
      isDistrict: !this.data.isDistrict
    }))
    this.init()
  },

  closeTap(){
    this.setData({ isNotice: false })
  },

  //信息弹窗
  noticeTap(){
    const id = this.data.article_window;
    newsapi({ id }).then(res => {
      app.globalData.webUrl = res.url
      wx.navigateTo({
        url: `../webView/webView?title=公告详情`
      })
    })
    this.setData({ isNotice: false })
  },

  // 轮播图跳转
  toWebTap(e) {
    const id = e.currentTarget.dataset.id || ''
    id && wx.navigateTo({
      url: `../detail/detail?item_id=${id}`,
    })
  },

  // 首页导航跳转
  toProduct(e){
    app.globalData.vanTab.itemsIndex = 0;
    app.globalData.vanTab.isNav = true;
    Object.assign(app.globalData.vanTab, e.currentTarget.dataset);
    wx.switchTab({
      url: '../product/product'
    })
  },

  // 拨打电话
  PhoneCall() {
    wx.makePhoneCall({
      phoneNumber: app.globalData.customer //仅为示例，并非真实的电话号码
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const is_open = app.globalData.is_open
    if (is_open == 1) {
      const location = app.globalData.location
      this.setData(location)
      this.init()
    }else{
      // 停止下拉刷新
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})